package com.gl.sass.mq.configure;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;

import com.gl.sass.mq.producer.RetryListenser;
import com.gl.sass.mq.producer.RocketMQProducer;
import com.gl.sass.mq.producer.retry.LimitDelayQueue;
import com.gl.sass.mq.producer.retry.RetryMessage;

/**
 * MQ重试自动配置
 * @author xiehong
 *
 */
public class MQRetryAutoConfigure {

    private static final Logger log = LoggerFactory.getLogger(MQRetryAutoConfigure.class);

    @Value("${mq.maxRetryTimes:3}")
    private int maxRetryTimes;

    @Bean
    public LimitDelayQueue<RetryMessage> limitDelayQueue() {
        log.info("创建MQ重试队列");
        return new LimitDelayQueue<>(2000);
    }

    @Bean
    public RetryListenser retryListenser(LimitDelayQueue<RetryMessage> limitDelayQueue,
                                         RocketMQProducer rocketMQProducer) {
        log.info("创建MQ重试监听器");
        return new RetryListenser(limitDelayQueue, rocketMQProducer, maxRetryTimes);
    }

    @Bean
    public BeanPostProcessor rocketMQProducerBeanPostProcessor(LimitDelayQueue<RetryMessage> limitDelayQueue) {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
                return bean;
            }

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof RocketMQProducer) {
                    RocketMQProducer producer = (RocketMQProducer)bean;
                    producer.setLimitDelayQueue(limitDelayQueue);
                    return producer;
                }
                return bean;
            }
        };
    }

}
